<style lang="less">
.ivu-select-dropdown-list {
  height: 200px;
  overflow-y: auto;
}
</style>
<template>
    <rui-page :defines="defines">
        <rui-query :label-width="150"
                   ref="searchForm"
                   :query="queryData"
                   :query-rows="searchFormOptions"
        >
        </rui-query>
        <Row>
            <Alert show-icon>
                已选择 <span class="select-count">{{selectCount}}</span> 项
                <a class="select-clear" @click="clearSelectAll">清空</a>
            </Alert>
        </Row>
        <rui-table
            :defineId="'userDefine'"
            :columns="userColumns"
            :fixedLeft="['action']"
            :showIndex="false"
            :select="true"
            :slots="[{key:'action',slot:'action'}]"
            @loadDatas="queryData"
            ref-query="searchForm"
            @on-selection-change="changeSelect"
            ref="userTable"
        >
            <template slot="toolBar">
                <Button @click="add" icon="md-add" type="primary">新增</Button>
                <Button @click="delAll" type="error">删除</Button>
                <Button @click="refresh" type="primary">刷新</Button>
            </template>
            <template slot="action" slot-scope="{ row }">
                <div>
                    <Button @click="edit(row)" size="small" type="primary">编辑</Button>
                    <Button type="error" size="small" @click="remove(row)">删除</Button>
                </div>
            </template>
        </rui-table>
        <Modal
            v-model="userModalVisible"
            :title="modalTitle"
            :width="660"
            :closable="false"
            :mask-closable="false"
            @on-ok="submitUser"
        >
            <rui-form :form-options="userFormOptions" :read-only="false" ref="userForm">
                <template slot="userId" slot-scope="{ key,data }">
                    <Select v-if="modalType===1" style="width: 200px" filterable v-model="data[key]" disabled
                            @on-change="perChange" :label-in-value="true" @on-open-change="queryProductSelectList($event)"> 
                        <Option v-for="item in userList"  :value="item.userId" :key="item.userId"
                                :label="item.userRealName">
                            <span style="margin-right:5px;">{{ item.userRealName }}</span>
                        </Option>
                    </Select>
                    <Select v-if="modalType===0" style="width: 200px" filterable v-model="data[key]" @on-change="perChange" @on-open-change="queryProductSelectList($event)"
                            :label-in-value="true">
                        <Option v-for="item in userList"  :value="item.userId" :key="item.userId"
                                :label="item.userRealName">
                            <span style="margin-right:5px;">{{ item.userRealName }}</span>
                        </Option>
                    </Select>
                </template>
                <template slot="appertainRegion" slot-scope="{ key,data }">
                    <Poptip v-if="modalType===0" trigger="click" placement="right" title="选择所属的区域" >
                        <div >
                            <Input type="textarea"  v-model="data[key]" style="margin-right:10px;width: 200px" readonly 
                                   placeholder="选择所属区域"/>
                            <Button icon="md-trash" @click="clearSelectAp">清空已选</Button>
                        </div>
                        <div slot="content" class="tree-bar">
                            <Input v-model="searchApKey" suffix="ios-search" @on-change="searchAp" 
                                   placeholder="输入区域名搜索"/>
                            <Tree :data="dataAp" multiple ref="treeAp" :load-data="loadApDataTree"
                                  @on-select-change="selectApTree"></Tree>
                        </div>
                    </Poptip>
                    <Poptip v-if="modalType===1" trigger="click" placement="right" title="选择所属区域" >
                        <div >
                            <Input type="textarea" v-model="data[key]" readonly
                                   style="width: 200px;" placeholder="选择所属区域"/>
                            <Button icon="md-trash" @click="clearSelectAp">清空已选</Button>
                        </div>
                        <div slot="content" class="tree-bar">
                            <Input v-model="searchApKey" suffix="ios-search" @on-change="searchApp"
                                   placeholder="输入区域名搜索"/>
                            <Tree :data="editAp" multiple ref="treeAp"
                                  @on-select-change="selectApTree"></Tree>
                        </div>
                    </Poptip>
                </template>
                <template slot="authorizeRegion" slot-scope="{ key,data }">
                    <Poptip trigger="click" v-if="modalType===0" placement="right" title="选择的授权区域">
                        <div>
                            <Input type="textarea" v-model="data[key]" readonly
                                   style="margin-right:10px;width: 200px;" placeholder="选择授权区域"/>
                            <Button icon="md-trash" @click="clearSelectAut">清空已选</Button>
                        </div>
                        <div slot="content" class="tree-bar">
                            <Input v-model="searchApKey" suffix="ios-search" @on-change="searchAu"
                                   placeholder="输入区域名搜索"/>
                            <Tree :data="dataAu" ref="treeAu" multiple :load-data="loadApDataTree"
                                  @on-select-change="selectAutTree"></Tree>
                        </div>
                    </Poptip>
                    <Poptip trigger="click" v-if="modalType===1" placement="right" title="选择授权区域" >
                        <div >
                            <Input type="textarea" v-model="data[key]" readonly
                                   style="margin-right:10px;width: 200px;" placeholder="选择授权区域"/>
                            <Button icon="md-trash" @click="clearSelectAut">清空已选</Button>
                        </div>
                        <div slot="content" class="tree-bar">
                            <Input v-model="searchApKey" suffix="ios-search" @on-change="searchAut"
                                   placeholder="输入区域名搜索"/>
                            <Tree :data="editAu" ref="treeAu" multiple
                                  @on-select-change="selectAutTree"></Tree>
                        </div>
                    </Poptip>
                </template>
            </rui-form>
            <div slot="footer">
                <Button size="small" @click="cancel">取消</Button>
                <Button type="primary" size="small" @click="submitUser">保存</Button>
            </div>
        </Modal>
    </rui-page>
</template>
<script>
    import userDefine from "./user-define";
    import {
        addUser,
        editUser,
        deleteUser,
        getUserListData,
    } from "_p/afs-channel/api/admin/user";

    import {
        initAll,
        initAppertainRegion,
        searchAppertainRegion
    } from "_p/afs-channel/api/admin/appertainRegion";
    import {
        getAllUserData,
    } from "@/projects/basic/api/admin/user";
    import {deepClone} from '@/libs/utils/ObjectClone';

    export default {
        name: "user-manage",
        data() {
            return {
                userModalVisible: false,
                deptId: [],
                userData: [],
                modalType: null,
                userList: [],
                searchKey: "",
                searchApKey: "",
                dataAp: [],
                editAp: [],
                dataAu: [],
                editAu: [],
                appIds: [],
                autIds: [],
                modalTitle: "用户新增",
                searchFormOptions: [
                    {defineId: "userDefine", fields: ["userRealName"]},
                ],
                userColumns: ["action", "userRealName", "appertainRegions", "authorizeRegions"],
                userFormOptions: [
                    {
                        grids: [
                            {
                                defineId: "userDefine",
                                span: 10,
                                fields: ["userId", "appertainRegions", "authorizeRegions",],
                                slots: [{key: 'userId', slotName: 'userId'},
                                    {key: 'appertainRegions', slotName: 'appertainRegion'},
                                    {key: 'authorizeRegions', slotName: 'authorizeRegion'}],
                            }
                        ]
                    }
                ],
                selectCount: 0,
            };
        },
        computed: {
            defines() {
                return [
                    {
                        id: "userDefine",
                        fields: userDefine
                    }
                ];
            }
        },
        methods: {
            init() {
                this.initAppertainData();
                this.initAutData();
            },
            queryData(queryData) {
                getUserListData(queryData).then(res => {
                    if (res.code === "0000") {
                        let {records, total} = res.data;
                        this.userData = records;
                        this.$refs.userTable.updateTableData(records, total);
                    }
                });
            },
            refresh() {
                this.$refs['userTable'].reloadData();
                this.clearSelectAll();
            },
            clearSelectAll() {
                this.$refs.userTable.getTable().selectAll(false);
            },
            getAllUser() {
                getAllUserData().then(res => {
                    if (res.code === "0000") {
                        this.userList = res.data;
                    }
                });
            },
            // 点击下拉触发的事件
            queryProductSelectList(val) {
                 this.getAllUser();
                console.log("点击触发下拉");
            },
            remove(v) {
                this.$Modal.confirm({
                    title: "确认删除",
                    content: "您确认要删除用户 " + v.userRealName + " ?",
                    onOk: () => {
                        deleteUser(v.userId).then(res => {
                            if (res.code === "0000") {
                                this.$Message.success(res.msg);
                                this.refresh();
                            }
                        });
                    }
                });
            },
            changeSelect(e) {
                this.selectList = e;
                this.selectCount = e.length;
            },
            delAll() {
                if (this.selectCount <= 0 || this.selectCount == undefined) {
                    this.$Message.warning("您还未选择要删除的数据");
                    return;
                }
                this.$Modal.confirm({
                    title: "确认删除",
                    content: "您确认要删除所选的 " + this.selectCount + " 条数据?",
                    onOk: () => {
                        let ids = [];
                        this.selectList.forEach(function (e) {
                            ids += e.userId + ",";
                        });
                        ids = ids.substring(0, ids.length - 1);
                        deleteUser(ids).then(res => {
                            if (res.code === "0000") {
                                this.$Message.success("操作成功");
                                this.refresh();
                            }
                        });
                    }
                });
            },
            getUserListData() {
                this.userData.forEach(e => {
                    for (let i = 0; i < this.userList.length; i++) {
                        if (e.userId === this.userList[i].userId) {
                            this.$delete(this.userList, i);
                        }
                    }
                })
            },
            add() {
                this.$refs.userForm.resetFrom();
                this.modalType = 0;
                this.modalTitle = "用户新增";
                // this.$refs.userForm.setAllFieldRequired(true);
                this.$nextTick(() => {
                    this.$refs.userForm.resetFrom();
                })
                this.getUserListData();
                this.userModalVisible = true;
            },
            edit(row) {
                this.modalType = 1;
                this.modalTitle = "用户编辑";
                this.$refs.userForm.setFiledValue("userId", row.userId);
                let app = [];
                let appId = [];
                row.appertainRegion.forEach(function (e) {
                    app += e.title + ',';
                    appId.push(e.id);
                });
                app = app.substring(0, app.length - 1);
                this.$refs.userForm.setFiledValue("appertainRegions", app);
                this.$refs.userForm.setFiledValue("appertainRegionId", appId);
                let aut = [];
                let autId = [];
                row.authorizeRegion.forEach(function (e) {
                    aut += e.title + ',';
                    autId.push(e.id);
                });
                if(aut.length>0){
                    aut = aut.substring(0, aut.length - 1);
                }
                this.$refs.userForm.setFiledValue("authorizeRegions", aut);
                this.$refs.userForm.setFiledValue("authorizeRegionId", autId);
                this.appIds = appId;
                this.autIds = autId;
                this.selectApp(appId);
                
                this.selectAut(autId);
                
                // this.$refs.userForm.setAllFieldRequired(true);
                this.getAllUser();
                this.userModalVisible = true;
            },
            selectApp(row) {
                initAll(row).then(res => {
                    if (res.code === "0000") {
                        res.data.forEach(function (e) {
                            if (e.status === '0') {
                                e.title = "[已禁用] " + e.title;
                                e.disabled = true;
                            }
                            if (e.children) {
                                e.children.forEach(r => {
                                    if (r.status === '0') {
                                        r.title = "[已禁用] " + r.title;
                                        r.disabled = true;
                                    }
                                });
                            }
                        });
                        this.editAp = deepClone(res.data);
                    }
                });
            },
            selectAut(row) {
                if(row==""||row==null||row==undefined){
                    row='0';
                }
                initAll(row).then(res => {
                    if (res.code === "0000") {
                        res.data.forEach(function (e) {
                            if (e.status === '0') {
                                e.title = "[已禁用] " + e.title;
                                e.disabled = true;
                            }
                            if (e.children) {
                                e.children.forEach(r => {
                                    if (r.status === '0') {
                                        r.title = "[已禁用] " + r.title;
                                        r.disabled = true;
                                    }
                                });
                            }
                        });

                        this.editAu = deepClone(res.data);
                    }
                });
            },
            searchApp() {
                // 搜索区域
                if (this.searchApKey) {
                    searchAppertainRegion({title: this.searchApKey}).then(res => {
                        if (res.code === "0000") {
                            res.data.forEach(function (e) {
                                if (e.status === '0') {
                                    e.title = "[已禁用] " + e.title;
                                    e.disabled = true;
                                }
                            });
                            this.editAp = deepClone(res.data);
                        }
                    });
                } else {
                    this.selectApp(this.appIds);
                }
            },
            searchAut() {
                // 搜索区域
                if (this.searchApKey) {
                    searchAppertainRegion({title: this.searchApKey}).then(res => {
                        if (res.code === "0000") {
                            res.data.forEach(function (e) {
                                if (e.status === '0') {
                                    e.title = "[已禁用] " + e.title;
                                    e.disabled = true;
                                }
                            });
                            this.editAu = deepClone(res.data);
                        }
                    });
                } else {
                    this.selectAut(this.autIds);
                }
            },
            initAppertainData() {
                initAppertainRegion('0').then(res => {
                    if (res.code === "0000") {
                        res.data.forEach(function (e) {
                            if (e.isParent === '1') {
                                e.value = e.id;
                                e.label = e.title;
                                e.loading = false;
                                e.children = [];
                            } else {
                                e.value = e.id;
                                e.label = e.title;
                            }
                            if (e.status === '0') {
                                e.label = "[已禁用] " + e.label;
                                e.disabled = true;
                            }
                        });
                        this.dataAp = res.data;
                    }
                });
            },
            initAutData() {
                initAppertainRegion('0').then(res => {
                    if (res.code === "0000") {
                        res.data.forEach(function (e) {
                            if (e.isParent === '1') {
                                e.value = e.id;
                                e.label = e.title;
                                e.loading = false;
                                e.children = [];
                            } else {
                                e.value = e.id;
                                e.label = e.title;
                            }
                            if (e.status === '0') {
                                e.label = "[已禁用] " + e.label;
                                e.disabled = true;
                            }
                        });
                        this.dataAu = res.data;
                    }
                });
            },
            searchAp() {
                // 搜索区域
                if (this.searchApKey) {
                    searchAppertainRegion({title: this.searchApKey}).then(res => {
                        if (res.code === "0000") {
                            res.data.forEach(function (e) {
                                if (e.isParent === '1') {
                                    e.loading = false;
                                    e.children = [];
                                }
                                if (e.status === '0') {
                                    e.title = "[已禁用] " + e.title;
                                    e.disabled = true;
                                }
                            });
                            this.dataAp = res.data;
                        }
                    });
                } else {
                    this.initAppertainData();
                }
            },
            searchAu() {
                // 搜索区域
                if (this.searchApKey) {
                    searchAppertainRegion({title: this.searchApKey}).then(res => {
                        if (res.code === "0000") {
                            res.data.forEach(function (e) {
                                if (e.isParent === '1') {
                                    e.loading = false;
                                    e.children = [];
                                }
                                if (e.status === '0') {
                                    e.title = "[已禁用] " + e.title;
                                    e.disabled = true;
                                }
                            });
                            this.dataAu = res.data;
                        }
                    });
                } else {
                    this.initAutData();
                }
            },
            loadApDataTree(item, callback) {
                initAppertainRegion(item.id).then(res => {
                    if (res.code === "0000") {
                        res.data.forEach(function (e) {
                            if (e.isParent === '1') {
                                e.loading = false;
                                e.children = [];
                            }
                            if (e.status === '0') {
                                e.title = "[已禁用] " + e.title;
                                e.disabled = true;
                            }
                        });
                        callback(res.data);
                    }
                });
            },
            selectApTree(v) {
                console.log("我选择的"+v)
                console.log(JSON.stringify(v));
                let app = [];
                let appId = [];
                this.$refs.treeAp.getSelectedNodes().forEach(e => {
                    console.log(e)
                    app += e.title + ',';
                    appId.push(e.id);
                });
                this.appIds = appId;
                if(app.length>0){
                    app = app.substring(0, app.length - 1);
                }
                this.$refs.userForm.setFiledValue("appertainRegions", app);
                this.$refs.userForm.setFiledValue("appertainRegionId", appId);
            },
            selectAutTree(v) {
                let aut = [];
                let autId = [];
                this.$refs.treeAu.getSelectedNodes().forEach(e => {
                    aut += e.title + ',';
                    autId.push(e.id);
                })
                this.autIds = autId;
                aut = aut.substring(0, aut.length - 1);
                this.$refs.userForm.setFiledValue("authorizeRegions", aut);
                this.$refs.userForm.setFiledValue("authorizeRegionId", autId);
            },
            clearSelectAp() {
                this.initAppertainData();
                this.$refs.userForm.setFiledValue("appertainRegionId", "");
                this.$refs.userForm.setFiledValue("appertainRegions", "");
            },
            clearSelectAut() {
                this.initAutData();
                this.$refs.userForm.setFiledValue("authorizeRegionId", "");
                this.$refs.userForm.setFiledValue("authorizeRegions", "");
            },
            cancel() {
                this.initAppertainData();
                this.initAutData();
                this.userModalVisible = false;
            },
            perChange(e) {
                if(this.userList.length>0){
                    for(var i = 0; i < this.userList.length; i++){
                        if(e.value==this.userList[i].userId){
                          console.log("我找到了用户名"+this.userList[i].username)
                        this.$refs.userForm.setFiledValue("username", this.userList[i].username);
                        break;
                        }
                    }
                }
                this.$refs.userForm.setFiledValue("userRealName", e.label);
            },
            submitUser() {
                this.$refs.userForm.getForm().validate(valid => {
                    if (valid) {
                        if (this.modalType === 0) {
                            addUser(this.$refs.userForm.getFormData())
                                .then(res => {
                                    if (res.code === "0000") {
                                        this.$Message.success(res.msg);
                                        this.userModalVisible = false;
                                        this.refresh();
                                        this.initAppertainData();
                                        this.initAutData();
                                    }
                                })
                                .catch(() => {
                                    this.refresh();
                                });
                        } else {
                            // 编辑
                            editUser(this.$refs.userForm.getFormData())
                                .then(res => {
                                    if (res.code === "0000") {
                                        this.$Message.success(res.msg);
                                        this.userModalVisible = false;
                                        this.refresh();
                                        this.initAppertainData();
                                        this.initAutData();
                                    }
                                })
                                .catch(() => {
                                    this.refresh();
                                });
                        }
                    }
                });
            }
        },
        mounted() {
            this.getAllUser();
            this.init();
            this.refresh();
        }
    };
</script>
